﻿using BatchCreateTestData.Module.BusinessObjects;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchCreateTestData.Module.Controllers {
  public class TStudentVc : ViewController {
    private SimpleAction fBatchCreateAction;
    public TStudentVc() : base() {
      // Target required Views (use the TargetXXX properties) and create their Actions.
      TargetViewType = ViewType.ListView;
      TargetObjectType = typeof(BusinessObjects.TStudentBo);

      fBatchCreateAction = new SimpleAction(this, "批量添加", "View");
      fBatchCreateAction.Execute += fBatchCreateAction_Execute;
    }

    private void fBatchCreateAction_Execute(object sender, SimpleActionExecuteEventArgs e) {

      // 采用这种添加方式，必须执行 ObjectSpace.Refresh(); 执行 View.Refresh(); 是无效的
      //var bNew = ObjectSpace.CreateObject<TStudentBo>();
      //bNew.Name = "ABC";
      //ObjectSpace.CommitChanges();
      //ObjectSpace.Refresh();

      // 采用这种添加方式，可以不执行 View.Refresh();  和 ObjectSpace.Refresh(); 执行和不执行的区别还需要有待学习...
      // 但最好是按照文档来做，执行View.Refresh();
      //var bNew2 = ObjectSpace.CreateObject<TStudentBo>();
      //bNew2.Name = "ABCD";
      //((ListView)View).CollectionSource.Add(bNew2);
      //ObjectSpace.CommitChanges();
      //View.Refresh();

      string[] bNames = ["A", "B", "C"];
      foreach (string bName in bNames) {
        TStudentBo bObject = ObjectSpace.FirstOrDefault<TStudentBo>(u => u.Name == bName);
        if (bObject == null) {
          bObject = ObjectSpace.CreateObject<TStudentBo>();
          bObject.Name = bName;
        }
      }
      ObjectSpace.CommitChanges();
      ObjectSpace.Refresh();
    }
    protected override void OnActivated() {
      base.OnActivated();
      // Perform various tasks depending on the target View.
    }
    protected override void OnDeactivated() {
      // Unsubscribe from previously subscribed events and release other references and resources.
      base.OnDeactivated();
    }
    protected override void OnViewControlsCreated() {
      base.OnViewControlsCreated();
      // Access and customize the target View control.
    }
  }
}
